import React, { useEffect, useState } from 'react'
import { PageHeader, Button, Modal, Form, Input, message ,Checkbox, Divider } from 'antd';
import moment from 'moment'
import E from 'wangeditor'
import "../assets/base.less"
import { ArticleAddApi, ArticleEdit, ArticleUpdateApi,ViewArticles } from '../request/api'
import { useParams, useNavigate, useLocation } from 'react-router-dom'
import axios from 'axios';

let editor = null
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['springboot', 'c#','python','java','spring', 'springmvc','css','c++'];
const defaultCheckedList = [];
export default function Edit() {
  
  const [contentHtml, setContentHtml] = useState('')
  const location = useLocation()
  const [title, setTitle] = useState('')
  const [summary, setSummary] = useState('')
  const [tagName,setTagName]=useState('')
  const [isModalVisible, setIsModalVisible] = useState(false);
  const navigate = useNavigate()
  const [form] = Form.useForm();
  const params = useParams()
  const [checkedList, setCheckedList] = useState(defaultCheckedList);
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const onChange = (list) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
    
  };

  const onCheckAllChange = (e) => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  // 处理请求数据
  const dealData = (code) => {
    setIsModalVisible(false); // 关闭对话框
    if (code === 200) {
      message.success("编辑成功!")
      setTimeout(() => {
        // 跳回list页面
        navigate('/article')
      }, 1500)
    } else {
      message.error("出错了!")
    }
  }

  // 对话框点击了提交
  const handleOk = () => {
    form
      .validateFields()    // validate校验   field字段

      .then((values) => {
        // form.resetFields();   // reset重置
        let { title, summary,tag} = values;
        // 地址栏有id代表现在想要更新一篇文章
        if (params.id) {
          // 更新文章的请求
          ArticleUpdateApi(
            { title, summary, contentHtml, bodyId: params.id,checkedList }).then(res => {
              if(res.code===200){
                message.success("保存成功!")
                setTimeout(() => {
                  // 跳回list页面
                  navigate('/article')
                }, 600)
              }
              else{
                message.error("保存失败!")
              }
            }
            )
        } else {
          // 添加文章的请求
          ArticleAddApi({ title, summary, contentHtml ,checkedList}).then(res => dealData(res.code))
        }
      })
      .catch(() => false);
  };

  // 模拟componentDidMount
  useEffect(() => {
    editor = new E('#div1')
    editor.config.onchange = (newHtml) => {
      setContentHtml(newHtml)
    }
    editor.create()

    // 根据地址栏id做请求
    if (params.id) {
      const id={bodyId:params.id}
      ArticleEdit(id).then(res => {
        
        if (res.code === 200) { 
          editor.txt.html(res.data.contentHtml) // 重新设置编辑器内容
          setTitle(res.data.title)
          setSummary(res.data.summary)
            defaultCheckedList.length=0
            res.data.tag.map((item,index)=>{
              plainOptions.map((check,i)=>{
              if(check===item.tagName){
                defaultCheckedList.push(item.tagName)
              }
            }
            )
             
            })
          
          
          
        }
      })
    }

    return () => {
      // 组件销毁时销毁编辑器  注：class写法需要在componentWillUnmount中调用
      
      editor.destroy()
    }
  }, [location.pathname])

  return (
    <div>
      <PageHeader
        ghost={false}
        onBack={params.id ? () => window.history.back() : null}
        title="文章编辑"
        //summary={"当前日期：" + moment(new Date()).format("YYYY-MM-DD")}
        extra={<Button key="1" type="primary" onClick={() => setIsModalVisible(true)}>提交</Button>}
      ></PageHeader>
      <div id="div1" className='div1' style={{ padding: '0 20px 0px', background: '#fff'}}></div>
      <Modal zIndex={99999} title="填写文章标题" visible={isModalVisible} onOk={handleOk} onCancel={() => setIsModalVisible(false)} okText="提交" cancelText="取消">
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          autoComplete="off"
          initialValues={{ title, summary,tagName}}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请填写标题' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="描述"
            name="summary"
            rules={[{ required: true, message: '请填写文章描述' }]}
          >
            <Input />
          </Form.Item>
          <>
          <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
            标签（全选）
          </Checkbox>
          <Divider />
          <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
        </>
        </Form>
      </Modal>
    </div>
  )
}
